import request from '@/utils/request'

// 摄像头相关API接口 - 连接到Python后端

/**
 * 创建摄像头
 * @param {Object} data 摄像头数据
 * @returns {Promise}
 */
export function createCamera(data) {
  // 转换前端数据格式到Python后端格式
  const backendData = {
    name: data.name,
    longitude: data.position?.longitude || data.longitude,
    latitude: data.position?.latitude || data.latitude,
    height: data.position?.height || data.height,
    location: data.location || '',
    rtsp_url: data.rtspUrl || data.rtsp_url || '',
    wvp_device_id: data.deviceId || data.wvp_device_id || '',
    wvp_channel_id: data.channelId || data.wvp_channel_id || '',
    description: data.description || '',
    ai_enabled: data.aiEnabled || false,
    ai_algorithms: data.aiAlgorithms || []
  }

  return request({
    url: '/api/v1/cameras',
    method: 'post',
    data: backendData
  }).then(response => {
    // 转换Python后端响应格式到前端格式
    return formatCameraResponse(response)
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 获取摄像头列表
 * @param {Object} query 查询参数
 * @returns {Promise}
 */
export function getCameraList(query = {}) {
  const params = {
    page: query.pageNum || query.page || 1,
    size: query.pageSize || query.size || 10,
    status: query.status,
    ai_enabled: query.aiEnabled,
    search: query.name || query.search,
    location: query.location
  }

  // 移除undefined值
  Object.keys(params).forEach(key => {
    if (params[key] === undefined || params[key] === '') {
      delete params[key]
    }
  })

  return request({
    url: '/api/v1/cameras',
    method: 'get',
    params: params
  }).then(response => {
    // 处理Python后端的响应格式
    let cameras = []
    let total = 0

    if (Array.isArray(response)) {
      // 直接返回数组的情况
      cameras = response
      total = response.length
    } else if (response.data && Array.isArray(response.data)) {
      // 包装在data字段中的情况
      cameras = response.data
      total = response.total || response.data.length
    } else if (response.rows && Array.isArray(response.rows)) {
      // 分页格式的情况
      cameras = response.rows
      total = response.total || response.rows.length
    } else if (response.items && Array.isArray(response.items)) {
      // items格式的情况
      cameras = response.items
      total = response.total || response.items.length
    }

    return {
      code: 200,
      msg: '查询成功',
      total: total,
      rows: cameras.map(formatCameraResponse)
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 获取摄像头详情
 * @param {string|number} id 摄像头ID
 * @returns {Promise}
 */
export function getCameraDetail(id) {
  return request({
    url: `/api/v1/cameras/${id}`,
    method: 'get'
  }).then(response => {
    return {
      code: 200,
      msg: '查询成功',
      data: formatCameraResponse(response)
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 更新摄像头信息
 * @param {string|number} id 摄像头ID
 * @param {Object} data 更新数据
 * @returns {Promise}
 */
export function updateCamera(id, data) {
  // 转换前端数据格式到Python后端格式
  const backendData = {
    name: data.name,
    longitude: data.position?.longitude || data.longitude,
    latitude: data.position?.latitude || data.latitude,
    height: data.position?.height || data.height,
    location: data.location,
    rtsp_url: data.rtspUrl || data.rtsp_url,
    wvp_device_id: data.deviceId || data.wvp_device_id,
    wvp_channel_id: data.channelId || data.wvp_channel_id,
    description: data.description,
    ai_enabled: data.aiEnabled,
    ai_algorithms: data.aiAlgorithms,
    status: data.status
  }

  // 移除undefined值
  Object.keys(backendData).forEach(key => {
    if (backendData[key] === undefined) {
      delete backendData[key]
    }
  })

  return request({
    url: `/api/v1/cameras/${id}`,
    method: 'put',
    data: backendData
  }).then(response => {
    return {
      code: 200,
      msg: '更新成功',
      data: formatCameraResponse(response)
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 删除摄像头
 * @param {string|number} id 摄像头ID
 * @returns {Promise}
 */
export function deleteCamera(id) {
  return request({
    url: `/api/v1/cameras/${id}`,
    method: 'delete'
  }).then(() => {
    return {
      code: 200,
      msg: '删除成功'
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 获取摄像头统计信息
 * @returns {Promise}
 */
export function getCameraStatistics() {
  return request({
    url: '/api/v1/cameras/statistics/summary',
    method: 'get'
  }).then(response => {
    return {
      code: 200,
      msg: '查询成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 批量更新摄像头状态
 * @param {Array} ids 摄像头ID数组
 * @param {string} status 新状态
 * @returns {Promise}
 */
export function batchUpdateCameraStatus(ids, status) {
  return request({
    url: '/api/v1/cameras/batch/status',
    method: 'put',
    data: {
      camera_ids: ids,
      status: status
    }
  }).then(() => {
    return {
      code: 200,
      msg: '批量更新成功'
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 获取摄像头播放URL (保留兼容性，但可能需要后端实现)
 * @param {string|number} id 摄像头ID
 * @returns {Promise}
 */
export function getCameraPlayUrl(id) {
  return getCameraDetail(id).then(response => {
    const camera = response.data
    if (camera.rtspUrl || camera.rtsp_url) {
      return {
        code: 200,
        msg: '获取成功',
        data: {
          url: camera.rtspUrl || camera.rtsp_url,
          type: 'rtsp'
        }
      }
    } else {
      throw new Error('摄像头未配置播放地址')
    }
  })
}

/**
 * 格式化摄像头响应数据 - 将Python后端格式转换为前端格式
 * @param {Object} camera Python后端摄像头数据
 * @returns {Object} 前端格式的摄像头数据
 */
function formatCameraResponse(camera) {
  if (!camera) return null

  return {
    id: camera.id,
    name: camera.name,
    position: {
      longitude: camera.longitude,
      latitude: camera.latitude,
      height: camera.height
    },
    longitude: camera.longitude,
    latitude: camera.latitude,
    height: camera.height,
    location: camera.location,
    rtspUrl: camera.rtsp_url,
    rtsp_url: camera.rtsp_url,
    deviceId: camera.wvp_device_id,
    wvp_device_id: camera.wvp_device_id,
    channelId: camera.wvp_channel_id,
    wvp_channel_id: camera.wvp_channel_id,
    description: camera.description,
    aiEnabled: camera.ai_enabled,
    ai_enabled: camera.ai_enabled,
    aiAlgorithms: camera.ai_algorithms,
    ai_algorithms: camera.ai_algorithms,
    status: camera.status,
    createdAt: camera.created_at,
    created_at: camera.created_at,
    updatedAt: camera.updated_at,
    updated_at: camera.updated_at
  }
}

/**
 * 格式化错误响应
 * @param {Object} error 错误对象
 * @returns {Object} 格式化的错误
 */
function formatErrorResponse(error) {
  if (error.response && error.response.data) {
    const errorData = error.response.data
    return {
      code: error.response.status || 500,
      msg: errorData.message || errorData.detail || '操作失败',
      data: null
    }
  }
  return {
    code: 500,
    msg: error.message || '网络错误',
    data: null
  }
}

// 重试机制装饰器
function withRetry(fn, maxRetries = 3, delay = 1000) {
  return async function (...args) {
    let lastError

    for (let i = 0; i < maxRetries; i++) {
      try {
        return await fn.apply(this, args)
      } catch (error) {
        lastError = error

        // 如果是客户端错误(4xx)，不重试
        if (error.response && error.response.status >= 400 && error.response.status < 500) {
          throw error
        }

        // 最后一次重试失败，抛出错误
        if (i === maxRetries - 1) {
          throw error
        }

        // 等待后重试
        await new Promise(resolve => setTimeout(resolve, delay * (i + 1)))
      }
    }

    throw lastError
  }
}

// 导出带重试机制的API函数
export const createCameraWithRetry = withRetry(createCamera)
export const getCameraListWithRetry = withRetry(getCameraList)
export const getCameraDetailWithRetry = withRetry(getCameraDetail)
export const updateCameraWithRetry = withRetry(updateCamera)

// 摄像头数据模板
export const CameraTemplate = {
  name: '',
  position: {
    longitude: 0,
    latitude: 0,
    height: 0
  },
  location: '',
  rtspUrl: '',
  deviceId: '',
  channelId: '',
  description: '',
  aiEnabled: false,
  aiAlgorithms: []
}